<?php
define('token','yhalpomxhys0183');
if ($_SERVER['REQUEST_METHOD']!== 'POST') {
    header('HTTP/1.0 404 Forbidden');
    exit;
}
$auth_token = isset($_POST['token'])? $_POST['token'] : null;
if ($auth_token === null) {
    header('HTTP/1.0 404 Forbidden');
    exit;
}
if($auth_token != token) {
    header('HTTP/1.0 404 Forbidden');
    exit;
}
require('config.php');
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {    
    echo "<script>alert('register failed'); window.location.href = './';</script>";
    exit();
}  
$response = [];
$user_name = $_POST['account'];
$pass_word = $_POST['password'];
$mail = $_POST['mail'];
if (empty($user_name) || empty($pass_word) || empty($mail)) {
    echo "<script>alert('register failed'); window.location.href = './';</script>";
    exit();
}
require('setting.php');
function generateUniqueId($conn, $length = 7) {
    $letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $id = '';
    $id .= $letters[rand(0, strlen($letters) - 1)];
    $length -= 1;
    do {
        $id = '';
        for ($i = 0; $i < $length; $i++) {
            $id .= $characters[rand(0, strlen($characters) - 1)];
        }
        $result = $conn->query("SELECT 1 FROM user WHERE id = '$id'");
        if ($result !== false && $result->num_rows > 0) {
            $id = '';
        } else {
            break;
        }
    } while ($id === '');
    return $id;
}
$sqlSelect = "SELECT 1 FROM user WHERE username = ?";
$stmt = $conn->prepare($sqlSelect);
$stmt->bind_param("s", $user_name);
if(!$stmt->execute()) {
    echo "<script>alert('register failed'); window.location.href = './';</script>";
    exit();
}
$result = $stmt->get_result();
if($result->num_rows > 0) {
    echo "<script>alert('register failed: This account has already been registered'); window.location.href = './';</script>";
    exit();
}
$id = generateUniqueId($conn);
if ($id === false) {
    echo "<script>alert('register failed'); window.location.href = './';</script>";
    exit();
}
$zero = 0;
$sqlInsert = "INSERT INTO user (`id`, `username`,`password` ,`bdmail`,`capacity`,`rate`,`rated`,`capacityed`,`vip`) VALUES (?, ?, ?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sqlInsert);
$vip = '1970-01-01 00:00:00';
$stmt->bind_param("ssssdddds", $id, $user_name, $pass_word, $mail,$setting_regist['capacity'],  $setting_regist['rate'],$zero, $zero,$vip);
if ($stmt->execute()) {
} else {
    echo "<script>alert('register failed'); window.location.href = './';</script>";
    exit();
}
$stmt->close();
$conn->close();
echo "<script>alert('register success'); window.location.href = './';</script>";
exit();
?>